package main;

public class ProgressStatus {

	private StatusMonitor mon;
	int progress = 0;
	boolean latched = false;
	private static final int GRANULARITY = 1;

	public String id;

	synchronized public int getProgress() {
		if (!latched) {
			try {
				wait();
			} catch (InterruptedException e) {
			}
		}
		latched = false;
		return progress;

	}

	public ProgressStatus(StatusMonitor m) {
		mon = m;
	}

	synchronized public void setProgress(int p) {
		if (p - progress >= GRANULARITY) {
			progress = p;
			latched = true;
			mon.update(String.format("%s:progress:%d", id, p));
			mon.pushEvent(new ProgressEvent(ProgressEvent.TYPE_PROGRESS, p, id,
					""));
			notify();
		}
	}

	synchronized public void pushMessage(String text) {
		latched = true;
		mon.update(String.format("%s: %s", id, text));
		mon.pushEvent(new ProgressEvent(ProgressEvent.TYPE_MESSAGE, -1, id,
				text));
		notify();
	}

	synchronized public void finish(double fitnessvalue) {
		mon.update(String.format("%s: complete, fitness %f", id, fitnessvalue));
		mon.pushEvent(new ProgressEvent(ProgressEvent.TYPE_FINISH, 100, id, ""));
		notify();
	}

	synchronized public void start(String msg) {

		mon.pushEvent(new ProgressEvent(ProgressEvent.TYPE_START, 100, id, msg));
		notify();
	}

}